﻿namespace S4sme.Web
{
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;

    using Elmah;

    using S4sme.Init;
    using S4sme.Web.Infrastructure.Elmah;
    using S4sme.Web.Infrastructure.Globalisation;

    using SharpLite.Web.Mvc.ModelBinder;

    public class MvcApplication : HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
        {
            // The ordering is important – ElmahHandledErrorLoggerFilter should be registered before the HandleErrorAttribute.
            filters.Add(new ElmahHandledErrorLoggerFilter()); 
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes) 
        {
            const string DefaultRouteUrl = "{controller}/{action}/{id}";
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            var defaultRouteValueDictionary = new RouteValueDictionary(new { controller = "Home", action = "Index", id = UrlParameter.Optional });
            
            routes.Add("DefaultGlobalised", new GlobalisedRoute(DefaultRouteUrl, defaultRouteValueDictionary));
            routes.Add("Default", new Route(DefaultRouteUrl, defaultRouteValueDictionary, new MvcRouteHandler()));
            /*routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // URL with parameters, Parameter defaults */
        }

        // ELMAH Filtering, which is useful for production to ommit loggin of not found resources
// ReSharper disable InconsistentNaming
        protected void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
// ReSharper restore InconsistentNaming
        {
            FilterError404(e);
        }

        /*
        protected void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs e)
        {
            FilterError404(e);
        }*/

// ReSharper disable InconsistentNaming
        protected void Application_Start() 
// ReSharper restore InconsistentNaming
        {
            log4net.Config.XmlConfigurator.Configure();

            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            DependencyResolverInitializer.Initialize();

            ModelBinders.Binders.DefaultBinder = new SharpModelBinder();
        }

        // Dismiss 404 errors for ELMAH
        private static void FilterError404(ExceptionFilterEventArgs e)
        {
            if (e.Exception.GetBaseException() is HttpException)
            {
                var ex = (HttpException)e.Exception.GetBaseException();
                if (ex.GetHttpCode() == 404)
                {
                    e.Dismiss();
                }
            }
        }
    }
}